//用户先关的小仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { SER_TOKEN, GET_TOKEN, ROVE_TOKEN } from '@/utils/token'
//引入常量路由
import { constantRoute } from '@/router/routes'
//创建用户小仓库
let useUserStore = defineStore('User', {
  //小仓库存储数据的地方
  state: () => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute, //仓库存储生成菜单需要的数组
      username: '',
      avatar: '',
    }
  },

  //异步逻辑的地方
  actions: {
    async userLogin(data: any) {
      //登录请求
      let result: any = await reqLogin(data)
      if (result.code == 200) {
        this.token = result.data
        SER_TOKEN(result.data)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //用户相关
    async userInfo() {
      let result: any = await reqUserInfo()
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return process.reject(new Error(result.data.message))
      }
    },
    //  退出登录
    async useLogout() {
      let result: any = await reqLogout()
      if (result.code == 200) {
        //退出登录需要发请求
        this.token = ''
        this.username = ''
        this.avatar = ''
        ROVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  //计算属性的错地方
  getters: {},
})

//获取小仓的数据需要暴露
export default useUserStore
